import { AutoComplete, Button, Cascader, Checkbox, Col, ConfigProvider, Form, Input, Row, Select, message } from "antd";
import { useCallback, useEffect, useState } from "react";
import {
	checkMessageCode,
	getAddressVoData,
	getCompanyInfo,
	getMessageCode,
	getMoreInfoConfig,
	submitForm,
} from "../../http/suppiler";
import CustomModal from "../Modal";
import "./index.scss";
import { AddressVoOption, FieldType, formItemStatus } from "./type";
import {
	CompanyInfo,
	clearNotNumber,
	fetchCompanyData,
	generateFormData,
	handleAddressVO,
	handleCompanyInfo,
	handleMoreInfoConfig,
} from "./util";
import { privacyPolicyLink } from "../../config";
import { debounce, getPageSourceInfo } from "../../../../shared/util";
import { submitFail, submitFailByField, submitFailBycCode, submitSuccess } from "../../http/goldlog";
let outSeconds = 60;
const CustomForm = () => {
	/**
	 * message info
	 */
	const [messageApi, contextHolder] = message.useMessage();
	const errorMessage = (content: string) => {
		messageApi.open({
			type: "error",
			content,
			className: "mobile-info-message-style",
			duration: 100,
		});
	};

	/**
	 * TODO: hole form
	 */
	const [form] = Form.useForm<FieldType>();
	const [isOpen, setIsOpen] = useState(false);
	const [isGettingCode, setIsGetting] = useState(false);
	const [codeStatus, setCodeStatus] = useState<formItemStatus>("validating" as formItemStatus);
	const [addressFrom, setWhereAddress] = useState<"api" | "user">("api");
	const [companyInfo, setCompanyInfo] = useState<CompanyInfo>();
	const [modalImgSrc, setImgSrc] = useState("");
	const codeValidate =
		codeStatus == "error"
			? {
					help: "验证码错误",
					validateStatus: "error",
			  }
			: {};

	const onFinish = async (values: FieldType) => {
		//check code
		try {
			await checkMessageCode({ phone: form.getFieldValue("phone"), messageCode: form.getFieldValue("code") });
		} catch (error) {
			console.log("check false"); //验证码错误
			setCodeStatus("error");
			/** TODO: log failed by code error */
			submitFailBycCode();
			return;
		}

		// submit form
		const formData = generateFormData(values, companyInfo!, addressFrom);
		try {
			const {
				values: { saleWeComQrUrl },
			} = await submitForm(formData as any);
			setImgSrc(saleWeComQrUrl || "");
			setIsOpen(true);
			/** TODO: log, submit success */
			submitSuccess();
		} catch (error) {
			/** TODO: log, submit failed, by fetch api error */
			submitFail("fetch_api_error");
			errorMessage(error as string);
		}
	};

	const onFinishFailed = (errorInfo: any) => {
		/** TODO: log failed by field error */
		submitFailByField();

		console.log("Failed:", errorInfo);
	};

	/**
	 * TODO: message code
	 */
	const [isOrange, setCodeIsOrange] = useState(false);
	const [seconds, setSeconds] = useState(60);
	const sendMessageCode = async () => {
		if (isGettingCode) return;

		try {
			await form.validateFields(["phone"]);
		} catch (error) {
			console.log(error);
			return;
		}
		setIsGetting(true);
		const intervalId = setInterval(() => {
			if (outSeconds > 0) {
				setSeconds(--outSeconds);
			} else {
				clearInterval(intervalId);
				setIsGetting(false);
				setSeconds(60);
				outSeconds = 60;
			}
		}, 1000);
		// setTimeout(() => setIsGetting(false), 1000 * 60); // 60s

		await getMessageCode({ phone: form.getFieldValue("phone") }).catch(console.log);
	};

	const clearFormData = () => {
		form.resetFields();
		setCodeStatus("validating");
	};

	/**
	 * TODO: Company Name
	 */
	const [isOpenSelect, setIsOpenSelect] = useState(false);
	const [selectCompanyOption, setCompanyOption] = useState<{ label: string; value: string }[]>([]);
	const [isDisplayAddress, setIsDisplay] = useState(false);

	const fetchCompanyDataDebounce = useCallback(
		debounce((newValue: string, callback: Function) => fetchCompanyData(newValue, callback), 300),
		[]
	);

	// search data
	const searchCompanysName = (newValue: string, callback: Function = () => 0) => {
		fetchCompanyDataDebounce(newValue, (options: any) => {
			setCompanyOption(options);
			callback();
		});
	};

	const selectOneCompany = (value: string) => {
		// get company info
		getCompanyInfo({ companyName: value }).then((res) => {
			const { addressVo, address } = handleCompanyInfo(res);
			form.setFieldValue("addressVo", addressVo);
			form.setFieldValue("address", address);
			setCompanyInfo(res.values);
			setIsDisplay(true);
		});
	};

	//company input
	const onChangeInput = (value: string) => {
		if (/^[\u4e00-\u9fa5]*$/.test(value))
			searchCompanysName(value, () => {
				setIsOpenSelect(true);
			});
	};

	useEffect(() => {
		if (form.getFieldValue("companyName") && isOpenSelect == false) {
			setIsDisplay(true);
		} else {
			setIsDisplay(false);
		}
	}, [isOpenSelect]);

	/**
	 * TODO: Address Vo
	 * 公司地址
	 */
	const [cascaderOption, setOption] = useState<AddressVoOption[]>([]);
	useEffect(() => {
		getAddressVoData({ reginId: 1 }).then((res) => {
			// console.log("address data useEffect: ", res);
			setOption(handleAddressVO(res));
		});
	}, []);

	const loadNextAddressVo = async (selectedOptions: AddressVoOption[]) => {
		// console.log(selectedOptions);
		const [temp] = selectedOptions.slice(-1);
		const divisionId = temp.value.split("_")[1];

		const res = await getAddressVoData({ reginId: divisionId });

		temp.children = handleAddressVO(res);
		setOption([...cascaderOption]);
	};

	/**
	 * TODO: 了解更多
	 */
	const [moreInfoOption, setMoreInfoOption] = useState<{ label: string; value: string; className?: string }[]>([]);
	useEffect(() => {
		//了解更多
		getMoreInfoConfig({
			origin: getPageSourceInfo().origin,
		}).then((res) => {
			setMoreInfoOption(handleMoreInfoConfig(res));
		});
	}, []);
	return (
		<div className='alibaba-custom-form-container'>
			{contextHolder}
			<ConfigProvider
				theme={{
					components: {
						Select: {
							optionSelectedBg: "rgba(0, 0, 0, 0.04)",
						},
						Cascader: {
							optionSelectedFontWeight: 500,
						},
					},
				}}>
				<Form
					form={form}
					name='basic'
					labelCol={{ span: 12 }}
					wrapperCol={{ span: 24 }}
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete='off'
					layout='vertical'
					onValuesChange={() => {
						console.log(form.getFieldValue("addressVo"), form.getFieldValue("companyName"));
					}}>
					<Form.Item<FieldType>
						label='公司名称'
						name='companyName'
						rules={[
							{
								required: true,
								message: "请正确填写五个汉字以上的公司名称",
								pattern: /^[\u4e00-\u9fa5]{5,}$/,
							},
						]}>
						<AutoComplete
							placeholder='请输入'
							id='form-input-company-name'
							className='mobile-company-name'
							onSearch={onChangeInput}
							onBlur={() => {
								if (form.getFieldValue("companyName")) setIsDisplay(true);
								else setIsDisplay(false);
							}}
							onSelect={(value: string) => {
								selectOneCompany(value);
								// setIsOpenSelect(false);
								// form.setFieldValue("companyName", value);
							}}
							options={selectCompanyOption}
							getPopupContainer={(e) => e}
						/>
					</Form.Item>

					<Form.Item<FieldType>
						label='姓名'
						name='username'
						rules={[{ required: true, message: "姓名不能为空" }]}>
						<Input placeholder='请输入' className='mobile-user-name' />
					</Form.Item>
					<Row gutter={9}>
						<Col span={15}>
							<Form.Item
								name='phone'
								label='电话号码'
								rules={[
									{ required: true, message: "请输入电话号码" },
									{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的电话号码" },
								]}
								normalize={clearNotNumber}>
								<Input
									addonBefore={<div>86</div>}
									suffix={
										<div
											className={`${
												isGettingCode
													? "get-code-button get-code-button-disable"
													: "get-code-button"
											}  ${isOrange && !isGettingCode ? "orange" : ""}
													`}
											onClick={sendMessageCode}>
											{isGettingCode ? seconds + "s重新获取" : "获取验证码"}
										</div>
									}
									placeholder='请输入'
									onChange={(e) => {
										if (/^1[3-9]\d{9}$/.test(e.target.value)) {
											setCodeIsOrange(true);
										} else {
											setCodeIsOrange(false);
										}
									}}
								/>
							</Form.Item>
						</Col>
						<Col span={9}>
							<Form.Item
								name='code'
								label='验证码'
								rules={[{ required: true, message: "请输入验证码" }]}
								{...(codeValidate as any)}>
								<Input
									className='mobile-message-code'
									placeholder='请输入'
									onChange={() => {
										setCodeStatus("validating");
									}}
								/>
							</Form.Item>
						</Col>
					</Row>

					{isDisplayAddress ? (
						<>
							{/* company info */}
							<Form.Item<FieldType>
								name={"addressVo"}
								label='公司地址'
								rules={[{ required: true, message: "请正确选择省/市/区/街道" }]}>
								<Cascader
									// open
									className='mobile-address-vo'
									popupClassName='form-item-cascader'
									loadData={loadNextAddressVo}
									options={cascaderOption}
									placeholder='请输入'
									placement={"bottomLeft"}
									onChange={(value: any, options: any) => {
										setWhereAddress("user");
									}}
									maxTagCount={"responsive"}
								/>
							</Form.Item>

							{/* company detail address */}
							<Form.Item<FieldType>
								label='详细地址'
								name='address'
								rules={[{ required: true, message: "请填写详细地址" }]}>
								<Input placeholder='请输入' className='mobile-detail-address' />
							</Form.Item>
						</>
					) : (
						""
					)}

					<Form.Item<FieldType>
						name='moreInfo'
						label='了解更多'
						valuePropName='value'
						className='form-item-selector'>
						<Select
							mode='multiple'
							placeholder='选择您关注的'
							options={moreInfoOption}
							popupClassName='alibaba-select-dropdown'
							className='mobile-multiple-more-info'
							menuItemSelectedIcon={null}
							showSearch={false}
							onChange={(value) => {
								// console.log("change: ", value);
								form.setFieldValue("moreInfo", value);
							}}
							optionRender={(options) => {
								return (
									<div>
										<Checkbox
											checked={form.getFieldValue("moreInfo")?.includes(options.data.value)}
										/>
										<span className='checkbox-span-text'>{options.data.label}</span>
									</div>
								);
							}}
							maxTagCount={"responsive"}
							getPopupContainer={(e) => e}
						/>
					</Form.Item>

					<Form.Item<FieldType>
						name='agree'
						valuePropName='checked'
						rules={[{ required: true, message: "未勾选", pattern: /true/ }]}
						className='form-item-more-info'>
						<Checkbox className='mobile-agree-policy'>
							<div className='more-info-message'>
								为向您提供个性化的营销服务，您知悉并同意Alibaba.com 会根据其
								<a className='orange' href={privacyPolicyLink}>
									《隐私权政策》
								</a>
								以及使用您的上述信息。
							</div>
						</Checkbox>
					</Form.Item>

					<Form.Item style={{ marginBottom: "0" }}>
						<div className='horizontal-vertical'>
							<Button type='primary' htmlType='submit' shape='round' className='consult-button'>
								开店咨询
							</Button>
						</div>
					</Form.Item>
				</Form>
				<CustomModal
					isOpen={isOpen}
					onCancel={() => {
						setIsOpen(false);
						clearFormData();
					}}
					imgSrc={modalImgSrc}
				/>
			</ConfigProvider>
		</div>
	);
};

export default CustomForm;
